package com.burst.reptile.framework.manager.factory;

import java.time.LocalDateTime;
import java.util.List;
import java.util.TimerTask;

import javax.servlet.http.HttpServletRequest;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.burst.reptile.common.constant.Constants;
import com.burst.reptile.common.utils.LogUtils;
import com.burst.reptile.common.utils.ServletUtils;
import com.burst.reptile.common.utils.ToolUtil;
import com.burst.reptile.common.utils.ip.AddressUtils;
import com.burst.reptile.common.utils.ip.IpUtils;
import com.burst.reptile.framework.config.SpringContextHolder;
import com.burst.reptile.modular.monitor.entity.SysLogininfor;
import com.burst.reptile.modular.monitor.entity.SysOperLog;
import com.burst.reptile.modular.monitor.service.ISysLogininforService;
import com.burst.reptile.modular.monitor.service.ISysOperLogService;
import com.burst.reptile.modular.zp.entity.ZpCollect;
import com.burst.reptile.modular.zp.entity.ZpHistory;
import com.burst.reptile.modular.zp.entity.ZpNotice;
import com.burst.reptile.modular.zp.entity.ZpResources;
import com.burst.reptile.modular.zp.entity.ZpVote;
import com.burst.reptile.modular.zp.service.IZpCollectService;
import com.burst.reptile.modular.zp.service.IZpHistoryService;
import com.burst.reptile.modular.zp.service.IZpNoticeService;
import com.burst.reptile.modular.zp.service.IZpResourcesService;
import com.burst.reptile.modular.zp.service.IZpVoteService;

import cn.hutool.http.useragent.UserAgent;
import cn.hutool.http.useragent.UserAgentUtil;
import lombok.extern.slf4j.Slf4j;

/**
 * 异步工厂（产生任务用）
 * @author ruoyi
 */
@Slf4j
public class AsyncFactory {

	/**
	 * 记录登陆信息
	 * 
	 * @param username 用户名
	 * @param status   状态
	 * @param message  消息
	 * @param args     列表
	 * @return 任务task
	 */
	public static TimerTask recordLogininfor(final String username, final String status, final String message,
			final Object... args) {
		final UserAgent userAgent = UserAgentUtil.parse(ServletUtils.getRequest().getHeader("User-Agent"));
		final String ip = IpUtils.getIpAddr(ServletUtils.getRequest());
		return new TimerTask() {
			@Override
			public void run() {
				String address = AddressUtils.getRealAddressByIP(ip);
				StringBuilder s = new StringBuilder();
				s.append(LogUtils.getBlock(ip));
				s.append(address);
				s.append(LogUtils.getBlock(username));
				s.append(LogUtils.getBlock(status));
				s.append(LogUtils.getBlock(message));
				// 打印信息到日志
				log.info(s.toString(), args);
				// 封装对象
				SysLogininfor logininfor = new SysLogininfor();
				if(ToolUtil.isNotEmpty(userAgent)) {
					// 获取客户端操作系统
					String os = userAgent.getOs().getName();
					// 获取客户端浏览器
					String browser = userAgent.getBrowser().getName();
					// 获取客户端浏览器 版本号
					String version = userAgent.getVersion();
					// 引擎类型
					String engine = userAgent.getEngine().getName();
					// 引擎版本号
					String engineVersion = userAgent.getEngineVersion();
					// 平台类型
					String platform = userAgent.getPlatform().getName();
					// 是否是移动平台
					boolean mobile = userAgent.isMobile();
					logininfor.setEngine(engine);
					logininfor.setEngineVersion(engineVersion);
					logininfor.setPlatform(platform);
					logininfor.setMobile(mobile ? "0" : "1");
					logininfor.setBrowser(browser);
					logininfor.setOs(os);
					logininfor.setBrowserVersion(version);
				}
				logininfor.setUserName(username);
				logininfor.setIpaddr(ip);
				logininfor.setLoginLocation(address);
				logininfor.setMsg(message);
				logininfor.setLoginTime(LocalDateTime.now());
				// 日志状态
				if (Constants.LOGIN_SUCCESS.equals(status) || Constants.LOGOUT.equals(status)) {
					logininfor.setLoginStatus(Constants.SUCCESS);
				} else if (Constants.LOGIN_FAIL.equals(status)) {
					logininfor.setLoginStatus(Constants.FAIL);
				}
				// 插入数据
				SpringContextHolder.getBean(ISysLogininforService.class).insertLogininfor(logininfor);
			}
		};
	}
	
	/**
	 * 记录登陆信息
	 * 
	 * @param username 用户名
	 * @param status   状态
	 * @param message  消息
	 * @param args     列表
	 * @return 任务task
	 */
	public static TimerTask recordLogininforLogout(final String username, final String status, final String message, final HttpServletRequest request,
			final Object... args) {
		final UserAgent userAgent = UserAgentUtil.parse(request.getHeader("User-Agent"));
		final String ip = IpUtils.getIpAddr(request);
		return new TimerTask() {
			@Override
			public void run() {
				String address = AddressUtils.getRealAddressByIP(ip);
				StringBuilder s = new StringBuilder();
				s.append(LogUtils.getBlock(ip));
				s.append(address);
				s.append(LogUtils.getBlock(username));
				s.append(LogUtils.getBlock(status));
				s.append(LogUtils.getBlock(message));
				// 打印信息到日志
				log.info(s.toString(), args);
				// 封装对象
				SysLogininfor logininfor = new SysLogininfor();
				if(ToolUtil.isNotEmpty(userAgent)) {
					// 获取客户端操作系统
					String os = userAgent.getOs().getName();
					// 获取客户端浏览器
					String browser = userAgent.getBrowser().getName();
					// 获取客户端浏览器 版本号
					String version = userAgent.getVersion();
					// 引擎类型
					String engine = userAgent.getEngine().getName();
					// 引擎版本号
					String engineVersion = userAgent.getEngineVersion();
					// 平台类型
					String platform = userAgent.getPlatform().getName();
					// 是否是移动平台
					boolean mobile = userAgent.isMobile();
					logininfor.setEngine(engine);
					logininfor.setEngineVersion(engineVersion);
					logininfor.setPlatform(platform);
					logininfor.setMobile(mobile ? "0" : "1");
					logininfor.setBrowser(browser);
					logininfor.setOs(os);
					logininfor.setBrowserVersion(version);
				}
				logininfor.setUserName(username);
				logininfor.setIpaddr(ip);
				logininfor.setLoginLocation(address);
				logininfor.setMsg(message);
				logininfor.setLoginTime(LocalDateTime.now());
				// 日志状态
				if (Constants.LOGIN_SUCCESS.equals(status) || Constants.LOGOUT.equals(status)) {
					logininfor.setLoginStatus(Constants.SUCCESS);
				} else if (Constants.LOGIN_FAIL.equals(status)) {
					logininfor.setLoginStatus(Constants.FAIL);
				}
				// 插入数据
				SpringContextHolder.getBean(ISysLogininforService.class).insertLogininfor(logininfor);
			}
		};
	}

	/**
	 * 操作日志记录
	 * 
	 * @param operLog 操作日志信息
	 * @return 任务task
	 */
	public static TimerTask recordOper(final SysOperLog operLog) {
		return new TimerTask() {
			@Override
			public void run() {
				// 远程查询操作地点
				operLog.setOperLocation(AddressUtils.getRealAddressByIP(operLog.getOperIp()));
				SpringContextHolder.getBean(ISysOperLogService.class).insertOperlog(operLog);
			}
		};
	}
	
	/**
	 * 操作消息记录
	 * 
	 * @param msg 操作消息信息
	 * @return 任务task
	 */
	public static TimerTask recordMsg(final ZpNotice m) {
		return new TimerTask() {
			@Override
			public void run() {
				SpringContextHolder.getBean(IZpNoticeService.class).insertNotice(m);
			}
		};
	}

	/**
	 * 阅读内容 新增浏览历史 和阅读数量
	 * @param data
	 * @param userId
	 * @return
	 */
	public static TimerTask recordRead(String data, Long userId) {
		return new TimerTask() {
			@Override
			public void run() {
				IZpResourcesService resourcesService = SpringContextHolder.getBean(IZpResourcesService.class);
				ZpResources byId = resourcesService.getById(data);
				if(ToolUtil.isNotEmpty(byId)) {
					// 新增浏览历史
					IZpHistoryService historyService = SpringContextHolder.getBean(IZpHistoryService.class);
					List<ZpHistory> list = historyService.list(new QueryWrapper<ZpHistory>().eq("article_id", byId.getArticleId()));
					if(ToolUtil.isNotEmpty(list)) {
						list.forEach(i -> {
							i.setCreateTime(LocalDateTime.now());
							historyService.updateById(i);
						});
					}else {
						ZpHistory history = new ZpHistory();
						history.setArticleId(byId.getArticleId());
						history.setUserId(userId);
						historyService.save(history);
					}
				}
			}
		};
	}

	/**
	 * 消息标记已读
	 * @param javaList
	 * @return
	 */
	public static TimerTask recordReadMsg(List<ZpNotice> javaList) {
		return new TimerTask() {
			@Override
			public void run() {
				IZpNoticeService noticeService = SpringContextHolder.getBean(IZpNoticeService.class);
				javaList.forEach(i -> {
					i.setSign("1");
					noticeService.updateById(i);
				});
			}
		};
	}

	/**
	 * 删除关联资源
	 * @param string 资源ID
	 * @return
	 */
	public static TimerTask delRelationRes(String string) {
		return new TimerTask() {
			@Override
			public void run() {
				// 点赞 收藏  历史
				IZpVoteService voteService = SpringContextHolder.getBean(IZpVoteService.class);
				voteService.remove(new QueryWrapper<ZpVote>().eq("article_id", string));
				IZpCollectService collectService = SpringContextHolder.getBean(IZpCollectService.class);
				collectService.remove(new QueryWrapper<ZpCollect>().eq("article_id", string));
				IZpHistoryService historyService = SpringContextHolder.getBean(IZpHistoryService.class);
				historyService.remove(new QueryWrapper<ZpHistory>().eq("article_id", string));
			}
		};
	}

	/**
	 * 新增阅读量
	 * @param data
	 * @return
	 */
	public static TimerTask incrRead(String data) {
		return new TimerTask() {
			@Override
			public void run() {
				IZpResourcesService resourcesService = SpringContextHolder.getBean(IZpResourcesService.class);
				ZpResources byId = resourcesService.getById(data);
				if(ToolUtil.isNotEmpty(byId)) {
					resourcesService.incrRead(byId.getArticleId());
				}
			}
		};
	}
	
}
